var ordercar = require("../../../class/user/carorder.c");
var member = require("../../../class/admin/memberinfo.c");
const KEY = 'm2wrFb48hbY3bMn7oG5NHCbcSpyQCuR2';
const APPID = 'wx97035d46a5a9b873';
const MCH_ID = '1377122102';
module.exports = {
    prefix: "/wx/core/",
    post: {
        "prpayid": {
            des: {
                name: "getWxAppPayPrePayId",
                content: "获取微信App支付prepay_id",
                params: [
                    {
                        key: "body = '';", // 商品描述
                        type: "string",
                        length: "128"
                    },
                    {
                        key: "out_trade_no", // 订单号
                        type: "string",
                        length: "32",
                        desc:'房车订单号'
                    },
                    {
                        key:'pay_type',
                        type:'int',
                        desc:'1、订单支付，2、会员支付'
                    }
                ]
            },
            method: function* () {
                var self = this;
                try {
                    //var data = yield parse(self.request.body);

                    var data = self.request.body;
                    var pay_type = data.pay_type?data.pay_type:1;
                    var send_data = {appid:APPID,mch_id:MCH_ID,key:KEY};
                    send_data.body = data.body?data.body:'租车订单支付';
                    if(pay_type==1){
                        send_data.attach = pay_type;
                        var orderobj =  new ordercar();
                        var carorder_data = yield orderobj.detail(data.out_trade_no);
                        if(!carorder_data){
                            self.body = printError("订单不存在！");
                            return false;
                        }
                        send_data.out_trade_no = carorder_data._id;
                        send_data.total_fee = carorder_data.price * 100;
                    }else{
                        send_data.attach = 2;
                        var obj_member =  new member();
                        var member_data = yield obj_member.detail(data.out_trade_no);
                        if(!member_data){
                            self.body = printError("会员申请不存在！");
                            return false;
                        }
                        if(member_data.status!=1){
                            self.body = printError("已经支付过了！");
                            return false;
                        }
                        if(member_data.type==1){
                            send_data.total_fee = 800 * 100;
                        }else if(member_data.type==2){
                            send_data.total_fee = 800 * 100;
                        }else if(member_data.type==3){
                            send_data.total_fee = 800 * 100;
                        }else{
                            self.body = printError("订单错误！");
                            return false;
                        }
                        send_data.out_trade_no = member_data._id;
                    }
                    
                    //send_data.openid = '1AOL9VIE6HOVURJ8BFAIL9RAK46Q8VLP';
                    send_data.spbill_create_ip = self.headers["x-forwarded-for"] || self.socket.remoteAddress;
                    send_data.trade_type = 'APP';
                    
                    send_data.notify_url = 'http://api.fangchepingtai.com/fangchebbs/pay_notify';
                    var str = '';
                    for(keys in send_data){
                        str += str==''?'':'&';
                        str += keys +'='+send_data[keys];
                    }
                    var url = "http://120.25.254.241:443/wx/core/prpayid?"+str;
                    var result = yield fetch(url, {
                        method: "GET",
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded"
                        }
                    });
                    self.body = result.body;
                    //self.body = send_data;
                   

                    /*data.notify_url = "http://wx.dotnar.com/wx/core/pay_notify";
                    data.nonce_str = $.randomString(32);
                    delete data.bus_id; // 过滤掉IOS版本默认发送的商户id字段，微信服务器不能解析此字段

                    var key = data.key,
                        json = {};

                    if (!data.prepay_id) {
                        data.total_fee = Math.floor(data.total_fee);
                        data.spbill_create_ip = self.headers["x-forwarded-for"] || self.socket.remoteAddress;
                        data.sign = WX.getSign(data); // 获取第一次参数签名
                        json = $.xml2json(yield WX.getPrepayId(data)); // 获取prepayid，并将微信返回的xml数据转为json
                    };

                    json.package = "Sign=WXPay";
                    json.partnerid = data.mch_id;
                    json.noncestr = data.nonce_str;
                    json.timestamp = Math.floor(new Date().getTime() / 1000);
                    json.signValue = WX.getSign({  // 创建第二次签名所需参数包
                        appid: data.appid,
                        package: "Sign=WXPay",
                        partnerid: data.mch_id,
                        prepayid: data.prepay_id || json.prepay_id,
                        noncestr: data.nonce_str,
                        key: key,
                        timestamp: json.timestamp
                    });
                    self.body = json;*/
                } catch (e) {
                    self.body = printError(e);
                };
            }
        },
        "pay_notify": {
            des: {
                name: "WXpayResultNotify",
                content: "微信支付结果通知回调，此接口为微信自动调用，不可人为调用"
            },
            method: function* () {
                var self = this;
                var data = self.request.body; // 微信支付结果返回的数据包
                var url = "http://120.25.254.241:443/wx/core/xml2json";
                var result = yield fetch(url, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    },
                    body:jsonTOurlencoded({xml:data.xml})
                });
                //var json_data = result.body;
                var json_data = yield result.json();
                json_data.appid = APPID;
                json_data.mch_id = MCH_ID;
                json_data.key = KEY;
                
                var old_sign = json_data.sign;
                if(!old_sign){
                    self.body = printError('签名错误');
                    return false;
                }
                delete json_data.sign;
                var new_sign = $.getSign(json_data);
                if(new_sign!=old_sign){
                    self.body = printError('签名错误');
                    return false;
                }
                if (json_data.result_code === "SUCCESS") {
                    //printSuccess("支付成功：", json);
                    var _id = json_data.out_trade_no;
                    if(json_data.attach==1){
                        
                        var orderobj =  new ordercar();
                        var result = yield orderobj.update(_id,2);
                        /*var result = yield fetch("http://api.dotnar.com/wx/app_pay_notify", {
                            method: "POST",
                            headers: {
                                "Content-Type": "application/x-www-form-urlencoded"
                            },
                            body: jsonTOurlencoded(json)
                        });
                        result = yield result.json();
                        console.log("result:", result);*/
                        self.body = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                    }else if(json_data.attach==2){
                        var memberobj =  new member();
                        var result = yield memberobj.detail(_id);
                        if(!result){
                            return false;
                        }
                        var result1 = yield memberobj.updateStatus(result);
                        self.body = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                    }
                    
                }
                
            }
        }
    },
    get: {
        /*"test": {
            des: {
                name: "getWxAppPayPrePayId",
                content: "获取微信App支付prepay_id",
                params: []
            },
            method: function* () {
                
            }
        }*/
    }
}